package org.lc.cmd.util;

import java.io.File;
import java.io.IOException;

public class ProcessUtil {
    public static boolean isWindows() {
        String os = System.getProperty("os.name").toLowerCase();
        return os.contains("win");
    }

    public static void executeInBackground(String[] command, File outputFile) {
        try {
            ProcessBuilder processBuilder;
            // 根据不同的操作系统使用不同的命令
            if (isWindows()) {
                // Windows
                String[] windowsCommand = new String[]{"cmd", "/c"};
                String[] fullCommand = new String[windowsCommand.length + command.length];
                System.arraycopy(windowsCommand, 0, fullCommand, 0, windowsCommand.length);
                System.arraycopy(command, 0, fullCommand, windowsCommand.length, command.length);
                processBuilder = new ProcessBuilder(fullCommand);
            } else {
                // Linux/Unix
                String[] linuxCommand = new String[]{"/bin/bash", "-c"};
                String[] fullCommand = new String[linuxCommand.length + command.length];
                System.arraycopy(linuxCommand, 0, fullCommand, 0, linuxCommand.length);
                System.arraycopy(command, 0, fullCommand, linuxCommand.length, command.length);
                processBuilder = new ProcessBuilder(fullCommand);
            }

            // 配置输出和错误流追加到文件
            processBuilder.redirectOutput(ProcessBuilder.Redirect.appendTo(outputFile));
            processBuilder.redirectError(ProcessBuilder.Redirect.appendTo(outputFile));

            // 启动进程
            processBuilder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
